package com.zhu.exception;

import com.zhu.pojo.entity.Result;
import jakarta.validation.ConstraintViolationException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class GloballExceptionHandler {

    /**
     * 参数校验
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        ex.printStackTrace();
        return Result.error(StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : "ConstraintViolationException: 未知错误");
    }

    /**
     * 实体类校验
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleConstraintViolationException(MethodArgumentNotValidException ex) {
        String message = ex.getMessage();
        System.out.println(message);
        Pattern p = Pattern.compile("default message \\[(.*?)\\]\\]");
        Matcher m = p.matcher(message);
        StringJoiner sj = new StringJoiner(" ");
        while (m.find()) {
            sj.add(m.group(1));
        }
        return Result.error(sj.toString());
    }
}
